﻿using EmitMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mitek.Services.Auth;
using Mitek.Web.Helpers;
using Mitek.Web.ViewModels;
using Mitek.Web.App_Start;
using Mitek.Web.Filters;
using Mitek.Web.Helpers;

namespace Mitek.Web.Areas.Admin.Controllers
{

    public class UserController : Controller
    {

        private readonly IUserService _userService;
        

        public UserController(IUserService userService)
        {
            this._userService = userService;
        }
        // GET: Admin/User
        [NormalAuthFilter(_role = (int)Mitek.Web.Helpers.Role.超级管理员)]
        public ActionResult Index(int? page = 1)
        {
            var users = _userService.GetUsers(page: (int)page, size: GlobalConfig.DefaultPageSize);
            var userViewModels = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<List<Mitek.Models.Auth.User>, List<ViewModels.UserViewModel>>().Map(users.ToList());

            var pagedList = new PagedList.StaticPagedList<UserViewModel>(userViewModels, users.GetMetaData());
            return View(pagedList);
        }

        #region 用户信息编辑
        [NormalAuthFilter(_role = (int)Mitek.Web.Helpers.Role.超级管理员)]
        public ActionResult Edit(int id)
        {
            var user = _userService.GetUserByID(id);
            return View(user);
        }

        [HttpPost]
        [NormalAuthFilter(_role = (int)Mitek.Web.Helpers.Role.超级管理员)]
        public ActionResult Edit(Mitek.Models.Auth.User user,FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (!string.IsNullOrEmpty(collection["NewPassWord"]))
                    {
                        user.PassWord = Utils.Security.Encrypt.Md5Encrypt(collection["NewPassWord"]); 
                    }
                    _userService.UpdateUser(user);
                }
                else
                {
                    throw new Exception();//this.ExtendErrors()
                }
            }
            catch (Exception e)
            {
                return Json(new
                {
                    statusCode = 500,
                    Msg = e.Message
                });
            }
            return Json(new
            {
                statusCode = 200,
                Msg = "编辑成功!",
                Url = "/admin/user/edit/" + user.ID + ""
            });
        }
        #endregion

        #region 用户登录
        [AllowAnonymousAttribute]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection collection)
        {
            try
            {
                if (string.IsNullOrEmpty(collection["Username"]) || string.IsNullOrEmpty(collection["Password"]))
                {
                    return Json(new
                    {
                        statusCode = 200,
                        Msg = "请填写完整的登录信息！"
                    });
                }
                else
                {
                    var user = _userService.GetUserByMobile(collection["Username"]);
                    if (user == null)
                    {
                        return Json(new
                        {
                            Msg = "该用户不存在！"
                        });
                    }
                    else
                    {
                        if (user.RoleID != (int)Mitek.Web.Helpers.Role.超级管理员)
                        {
                            return Json(new
                            {
                                Msg = "您还不是管理员，无权限操作！"
                            });
                        }
                        else
                        {
                            var re = _userService.UserLogin(collection["Username"], collection["Password"]);
                            if (re == null)
                                return Json(new { Msg = "登录失败,用户名或密码不正确，请稍后重试..." });

                            var userviewmodel = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Mitek.Models.Auth.User, ViewModels.ApplicationUser>().Map(re);

                            SessionContext.SignIn(userviewmodel);
                            return Json(new { Msg = "登录成功,页面正在跳转...", Url = "/admin/user/index/" });
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return Json(new
                {
                    statusCode = 500,
                    Msg = e.Message
                });
            }

        }
        #endregion

        public ActionResult Logout()
        {
            SessionContext.SignOut();
            return RedirectToAction("Login", "User", new { area = "admin" });
        }
    }
}